package com.heer.gymnasium.module.login.views;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.R;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.login.beans.RegisterBean;
import com.heer.gymnasium.module.login.beans.VerificationBean;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.util.StringUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by heer on 17/3/28.
 */

public class RegisterActivity extends BaseActivity {
    @BindView(R.id.edit_account)
    EditText editAccount;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.edit_verification_code)
    EditText editVerificationCode;
    @BindView(R.id.btn_request_code)
    Button btnRequestCode;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.btn_visible)
    ImageView btnVisible;

    Timer timer;
    TimerTask task;
    int time;
    String mUnionId;

    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if ((int)msg.obj ==0) {
                timer.cancel();
                task.cancel();
                btnRequestCode.setText("获取验证码");
                btnRequestCode.setClickable(true);
                btnRequestCode.setBackground(getResources().getDrawable(R.drawable.shape_main_color));
            } else {
                btnRequestCode.setText(msg.obj+"s 后可再次获取");
            }
        }
    };


    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.layout_register);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("注册");
        btnVisible.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 显示密码
                        editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        editPassword.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence = editPassword.getText();
                        if (charSequence != null) {
                            Spannable spanText = (Spannable) charSequence;
                            Selection.setSelection(spanText, charSequence.length());
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        // 隐藏密码
                        editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        editPassword.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence1 = editPassword.getText();
                        if (charSequence1 != null) {
                            Spannable spanText = (Spannable) charSequence1;
                            Selection.setSelection(spanText, charSequence1.length());
                        }
                        break;
                }
                return false;
            }
        });

        Bundle bdl = getIntent().getExtras();
        if(bdl!=null){
            mUnionId = bdl.getString("wx_id");
        }else{
            mUnionId = "";
        }
    }

    @OnClick({R.id.btn_request_code, R.id.btn_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request_code:

                mAppHelper.apiService().sendVerificationCode(editAccount.getText().toString().trim()).enqueue(new BaseCallback<ApiResponse<VerificationBean>>() {
                    @Override
                    public void onSuccess(Call<ApiResponse<VerificationBean>> call, Response<ApiResponse<VerificationBean>> response) {
                        if(response.isSuccessful()&&!response.body().isSccessful()){
                            return;
                        }
                        Log.e(TAG, "onResponse: " + response.body().getMsg());
                        btnRequestCode.setClickable(false);
                        btnRequestCode.setBackground(getResources().getDrawable(R.drawable.shape_gray));
                        time=60;
                        timer=new Timer();
                        task=new TimerTask() {
                            @Override
                            public void run() {
                                    time--;
                                    Message msg=new Message();
                                    msg.obj=time;
                                    handler.sendMessage(msg);
                            }
                        };
                        timer.schedule(task,0,1000);
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<VerificationBean>> call, Throwable t) {
                        new SVProgressHUD(mContext).showSuccessWithStatus("获取验证码有误");
                        Log.e(TAG, "onResponse: ");
                    }
                });
                break;
            case R.id.btn_register:
                String mPhone = editAccount.getText().toString().trim();
                String mPassword = editPassword.getText().toString().trim();
                String mCode = editVerificationCode.getText().toString().trim();
                if (StringUtils.isMobile(mPhone)) {
                    if (mPassword.length() >= 6 && mPassword.length() <= 18) {
                        mAppHelper.apiService().toRegister(mPhone, mPassword, mCode, mUnionId).enqueue(new BaseCallback<ApiResponse<RegisterBean>>() {
                            @Override
                            public void onSuccess(Call<ApiResponse<RegisterBean>> call, Response<ApiResponse<RegisterBean>> response) {
                                if(response.isSuccessful()&&!response.body().isSccessful()){
                                    new SVProgressHUD(mContext).showErrorWithStatus(response.body().getMsg());
                                    return;
                                }
                                new SVProgressHUD(mContext).showSuccessWithStatus("注册成功");
                                Session.setSessionKey(response.body().getData().getToken());
                                Session.setUserPhone(response.body().getData().getPhone());
                                SignHelper.initToken(Session.getSessionKey());
                                activityStartUtils.skipActivity(MainActivity.class);
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<RegisterBean>> call, Throwable t) {
                                super.onFailure(call, t);
                                new SVProgressHUD(mContext).showErrorWithStatus("请求失败");
                            }
                        });
                    } else {
                        new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.password_error));
                    }
                } else {
                    new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.account_error));
                }
                break;
        }
    }
}
